package com.mqtt.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 消息解析器
 */
@Slf4j
@Component
public class MessageParser {
    
    /**
     * 解析消息
     */
    public JSONObject parse(String message) {
        try {
            // 尝试JSON解析
            return JSON.parseObject(message);
        } catch (Exception e) {
            // 如果不是JSON，包装成JSON
            JSONObject result = new JSONObject();
            result.put("rawData", message);
            result.put("parseError", e.getMessage());
            return result;
        }
    }
    
    /**
     * 解析并验证消息
     */
    public Map<String, Object> parseAndValidate(String message, MessageSchema schema) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            JSONObject json = parse(message);
            
            // 验证必需字段
            for (String requiredField : schema.getRequiredFields()) {
                if (!json.containsKey(requiredField)) {
                    result.put("valid", false);
                    result.put("error", "Missing required field: " + requiredField);
                    return result;
                }
            }
            
            // 验证字段类型
            for (Map.Entry<String, Class<?>> entry : schema.getFieldTypes().entrySet()) {
                String field = entry.getKey();
                Class<?> expectedType = entry.getValue();
                
                if (json.containsKey(field)) {
                    Object value = json.get(field);
                    if (!expectedType.isInstance(value)) {
                        result.put("valid", false);
                        result.put("error", "Invalid type for field: " + field);
                        return result;
                    }
                }
            }
            
            result.put("valid", true);
            result.put("data", json);
            
        } catch (Exception e) {
            result.put("valid", false);
            result.put("error", "Parse error: " + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 提取特定字段
     */
    public Object extractField(String message, String fieldPath) {
        try {
            JSONObject json = parse(message);
            
            // 支持嵌套字段访问，如 "data.temperature"
            String[] parts = fieldPath.split("\\.");
            Object current = json;
            
            for (String part : parts) {
                if (current instanceof JSONObject) {
                    current = ((JSONObject) current).get(part);
                } else {
                    return null;
                }
            }
            
            return current;
            
        } catch (Exception e) {
            log.error("Error extracting field: {}", fieldPath, e);
            return null;
        }
    }
    
    /**
     * 消息模式定义
     */
    public static class MessageSchema {
        private String[] requiredFields;
        private Map<String, Class<?>> fieldTypes;
        
        public MessageSchema(String[] requiredFields, Map<String, Class<?>> fieldTypes) {
            this.requiredFields = requiredFields;
            this.fieldTypes = fieldTypes;
        }
        
        public String[] getRequiredFields() {
            return requiredFields;
        }
        
        public Map<String, Class<?>> getFieldTypes() {
            return fieldTypes;
        }
    }
}